package com.example.servlet;

import com.example.dao.UserDao;
import com.example.dao.UserDaoImpl;
import com.example.dao.AdminDao;
import com.example.dao.AdminDaoImpl;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "LoginServlet", value = "/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        String userType = request.getParameter("userType");
        String message = null;

        try {
            if ("user".equals(userType)) {
                // 普通用户登录
                boolean success = handleUserLogin(request, response);
                if (!success) {
                    message = "<li style='color:red;'>无该普通用户，请检查用户名</li>";
                }
            } else if ("admin".equals(userType)) {
                // 管理员登录
                boolean success = handleAdminLogin(request, response);
                if (!success) {
                    message = "<li style='color:red;'>无该管理员，请检查账号</li>";
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            message = "<li style='color:red;'>数据库错误：" + e.getMessage() + "</li>";
        }

        // 登录失败，返回提示信息
        if (message != null) {
            request.setAttribute("loginResult", message);
            RequestDispatcher rd = request.getRequestDispatcher("/login.jsp");
            rd.forward(request, response);
        }
    }

    /**
     * 处理普通用户登录逻辑
     */
    private boolean handleUserLogin(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        UserDao userDao = new UserDaoImpl();
        if (userDao.isUsernameExists(username)) {
            HttpSession session = request.getSession();
            session.setAttribute("user", username);
            session.setAttribute("userType", "user");

            // 登录后重定向到原始请求页面或主页
            String redirectUrl = (String) session.getAttribute("redirectUrl");
            if (redirectUrl != null && !redirectUrl.isEmpty()) {
                session.removeAttribute("redirectUrl");
                response.sendRedirect(redirectUrl);
            } else {
                response.sendRedirect(request.getContextPath() + "/jsp/Homepage.jsp");
            }

            return true;
        }
        return false;
    }


    /**
     * 处理管理员登录逻辑
     */
    private boolean handleAdminLogin(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, IOException {
        String username = request.getParameter("adminUsername");


        AdminDao adminDao = new AdminDaoImpl();
        if (adminDao.isAdminnameExists(username)) { // 假设添加validateAdmin方法验证用户名密码
            HttpSession session = request.getSession();
            session.setAttribute("admin", username);
            session.setAttribute("userType", "admin");

            // 登录后重定向到原始请求页面或主页
            String redirectUrl = (String) session.getAttribute("redirectUrl");
            if (redirectUrl != null && !redirectUrl.isEmpty()) {
                session.removeAttribute("redirectUrl");
                response.sendRedirect(redirectUrl);
            } else {
                response.sendRedirect(request.getContextPath() + "/jsp/AdminHomepage.jsp");
            }

            return true;
        }
        return false;
    }
}
